package com.ojoin.ojoin.eb_spider.service.catchdata;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.ojoin.ojoin.eb_spider.domain.BankCardCheck;
import com.ojoin.ojoin.eb_spider.service.SupplyInventoryService;
import com.ojoin.ojoin.eb_spider.service.SupplyPaymentService;
import com.ojoin.ojoin.eb_spider.service.impl.SLDataCatchBaseServiceImpl;
import com.ojoin.trade.common.exception.BusinessException;
import com.ojoin.trade.common.utils.CommonUtils;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.utils.NumberUtils;
import com.ojoin.trade.common.utils.TimeUtils;
import com.ojoin.trade.common.utils.WaitUtil;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlSupplyInventory;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlSupplyPayment;

/**
 * 
 ** 中粮我买网供应商平台数据抓取服务
 * 
 * 抓取数据逻辑： 1、已出结算单未付款数据：在未结算清单页面抓取未付款和未核对的单据
 * 2、采购入库未结算数据：根据结算单最大日期查询其上个月15号之后的采购入库单，抓取采购订单id不在已出结算单中的采购订单
 * 
 */

@Service
public class SupplierWOMAIDataCatchServiceImpl extends
		SLDataCatchBaseServiceImpl {
	private Logger log = LoggerFactory
			.getLogger(SupplierSFBESTDataCatchServiceImpl.class);

	@Autowired
	private SupplyPaymentService paymentService;

	@Autowired
	private SupplyInventoryService inventoryService;
	// 保存公司基本信息 key name 名字 bankNum 结款账号
	// lastTime 最近结算日期 lastTimeUrl
	Map<String, String> globalMap = new HashMap<String, String>();

	@Override
	public boolean LoginByUserInfo(String baseUrl, String username,
			String password) throws Exception {
		if (isCacheLogin()) {
			return true;
		}

		int loginCount = 1;
		// 开始登陆
		// 开始登陆 最多登陆三次（验证码错误情况）
		String loginReturnMess = ""; // 登陆返回信息
		while (loginCount < verifycodeRetryCount) {
			this.getWebDriver().get(baseUrl);
			loginCount++;

			try {
				this.getWebDriver().sendKeys("id", "username", username);
				this.getWebDriver().sendKeys("id", "password", password);
				this.verifycode();
				// 记录验证码请求次数
				this.getWebDriver().findElement("id", "doLogin").click();
				// loginsubmit.sendKeys(Keys.ENTER);
				// 页面跳转等待时间，不可删除
				WaitUtil.waitTimeSeconds(10);
				if (this.getWebDriver().isLogin(
						"http://i.womaiapp.com/index.action")) {
					return true;
				}
				WebElement webLoginReturnMess = this.getWebDriver()
						.findElement("id", "msg");
				loginReturnMess = webLoginReturnMess.getText();

			} catch (Exception e) {
				// 异常可忽略
				LogUtils.info(log,  this.getAssistCatchData().getStartMess().getPlatformUser()
						.getPlatformName()
						+ "-->username" + username + "登陆-->出现验证码%s ");
			}

			if ("验证码有误！".trim().equals(loginReturnMess.trim())
					|| CommonUtils.isEmpty(loginReturnMess.trim())) {
				continue;
			} else {
				break;
			}
		}

		return false;
	}

	// 验证码处理
	public void verifycode() throws Exception {
		LogUtils.info(log,  this.getAssistCatchData().getStartMess().getPlatformUser()
				.getPlatformName()
				+ " 登陆界面包含验证码.");
		WebElement verifyE = this.getWebDriver()
				.findElement("id", "captchaImg");

		if (null != verifyE) {

			String code = this.getWebDriver().getVerifyCodeByDMV3(verifyE);

			WebElement verifycode = this.getWebDriver().findElement("id",
					"captcha");

			this.getWebDriver().clearByJS(verifycode);
			verifycode.sendKeys(code);

			LogUtils.info(log,  this.getAssistCatchData().getStartMess().getPlatformUser()
					.getPlatformName()
					+ "verifyCode->" + code);

		}

	}

	@Override
	public String catchSupplierName() throws BusinessException {
		initCompanyInfomation();
		String name = "";
		if (null != globalMap) {
			name = globalMap.get("name");
		}
		return name;
	}

	@Override
	public BankCardCheck catchSupplierAccount() throws BusinessException {
		 BankCardCheck bcc = new BankCardCheck();
		initCompanyInfomation();
		String bankNum = "";
		if (null != globalMap) {
			bankNum = globalMap.get("bankNum");
		}

		bcc.setBankNum(bankNum);
		
		return bcc;
	}

	public Map<String, String> initCompanyInfomation() {

		String contractUrl = "http://supplier.i.womaiapp.com/update/getContractList.action";

		this.getWebDriver().get(contractUrl);

		WebElement a = this
				.getWebDriver()
				.findElement("css",
						"#mainframe div.o-con  div  table  tbody  tr:nth-child(2)  td:nth-child(8)  a");

		this.getWebDriver().clickByJS(a);

		WebElement webname = this
				.getWebDriver()
				.findElement("css",
						"#mainframe > div.o-con > div.i-info24 > div > p:nth-child(12)");

		WebElement webbankNum = this
				.getWebDriver()
				.findElement("css",
						"#mainframe > div.o-con > div.i-info24 > div > p:nth-child(13)");

		String name = webname.getText();
		String bankNum = webbankNum.getText();

		globalMap.put("name", name);
		globalMap.put("bankNum", bankNum);

		return globalMap;
	}

	@Override
	public boolean getUnpayAccountData() throws BusinessException {
		List<TbSlSupplyPayment> payments = new ArrayList<TbSlSupplyPayment>();

		Map<String, TbSlSupplyPayment> waitpay =  this.getAssistCatchData().getStartMess()
				.getWaitpay();

		String fiveDayPurchase = "http://supplier.i.womaiapp.com/statement/queryStatementList.action";

		this.getWebDriver().get(fiveDayPurchase);

		WebElement web = this.getWebDriver().findElement("id", "statementTr");

		List<WebElement> trs = web.findElements(By.tagName("tr"));

		if (null != trs && !trs.isEmpty()) {
			Iterator<WebElement> it = trs.iterator();
			while (it.hasNext()) {
				WebElement tr = it.next();
				// LogUtils.info(log,tr.getText());
				TbSlSupplyPayment payment = new TbSlSupplyPayment();
				payment.setPlatformAccountId( this.getAssistCatchData().getStartMess()
						.getPlatformUser().getId());

				try {
					List<WebElement> tds = tr.findElements(By.tagName("td"));
					// LogUtils.info(log,tds.get(6).getText());

					WebElement invoiceid = tds.get(1);
					WebElement webstatues = tds.get(10);
					WebElement webendtime = tds.get(11);
					WebElement Invoicetatol = tds.get(2);

					String endtime = webendtime.getText();
					String settlementId = invoiceid.getText();

					String amountD = Invoicetatol.getText();
					String statues = webstatues.getText();

					if (!"财务审核通过".equals(statues) && !"待付款".equals(statues)) {
						continue;
					}

					amountD = amountD.replace(",", "");

					long amount = NumberUtils.getLongAmount(amountD);
					payment.setSettlementId(settlementId);
					payment.setCreateDate(endtime);
					payment.setAmount(amount);
					payment.setSettlementState(TbSlSupplyPayment.WAITPAY);

					payments.add(payment);

				} catch (Exception e) {
					if (trs.size() != 1) {
						LogUtils.error(log, e);
					}
				}
			}
		}

		paymentService.removeSettlementCommon(payments, waitpay);
		List<TbSlSupplyPayment> li = paymentService.changeToPay(waitpay);
		 this.getAssistCatchData().getCata().setPayupdate(li);
		 this.getAssistCatchData().getCata().setSettlement(payments);

		return true;

	}

	@Override
	public boolean getInstoreOrderData() throws BusinessException {
		// 送货记录
		// 对账单

		String startime =  this.getAssistCatchData().getStartMess().getStoreInStartTime();
		String etime =  this.getAssistCatchData().getStartMess().getStoreInEndTime();

		List<TbSlSupplyInventory> list = new ArrayList<TbSlSupplyInventory>();
		Map<String, TbSlSupplyInventory> map =  this.getAssistCatchData().getStartMess().getStoreIn();

		String purchaseOrderUrl = "http://procurement.i.womaiapp.com/pro/procurementOrderList.action?orderType=-1&fresh=-1";
		this.getWebDriver().get(purchaseOrderUrl);

		this.getWebDriver().sendKeys("id", "operatorTime", startime);
		this.getWebDriver().sendKeys("id", "endDate", etime);

		this.getWebDriver().click("id", "button5");

		boolean flag = true;

		while (flag) {

			flag = catchPurchaseOrderDataExcludeBalance(startime, list);

			try {
				this.getWebDriver().click("css",
						"#mainframe > div.o-con > div > div > a.next");
			} catch (Exception e) {
				LogUtils.info(log, "最后一页，无下一页");
				break;
			}

		}

		inventoryService.removeInventoryCommon(list, map);

		 this.getAssistCatchData().getCata().setInstore(list);
		return true;
	}

	private boolean catchPurchaseOrderDataExcludeBalance(String startime,
			List<TbSlSupplyInventory> list) {
		try {

			WebElement tbody = this
					.getWebDriver()
					.findElement("css",
							"#mainframe > div.o-con > div > table > tbody:nth-child(2)");

			List<WebElement> trs = tbody.findElements(By.tagName("tr"));

			for (WebElement row : trs) {

				List<WebElement> tds = row.findElements(By.tagName("td"));

				String receiveStatus = tds.get(3).getText();
				String storedate = tds.get(9).getText().substring(0, 10);
				String itemid = tds.get(1).getText();
				// LogUtils.info(log, "itemid->" + itemid);
				// 收货状态正确、有效状态正确、采购日期在最大结算上月15号日期后、采购订单号不包括在结算单中

				if ((TimeUtils.getDateSpaceOfDay(startime, storedate)) < 0) {
					return false;
				}
				if (receiveStatus != null
						&& (receiveStatus.equals("部分收货") || receiveStatus
								.equals("完全收货"))
				// && validateStatus != null
				// && validateStatus.equals("有效")
				// && (TimeUtils.getDateSpace(lastMonthDate,
				// eachOrderDate)) > 0
				// && !purchaseOrderIDsInBalance.contains(itemid)
				) {

					LogUtils.info(log, "insert itemid->" + itemid);
					String ordercost = tds.get(15).getText();

					TbSlSupplyInventory vo = new TbSlSupplyInventory();
					vo.setPlatformAccountId( this.getAssistCatchData().getStartMess()
							.getPlatformUser().getId());
					vo.setItemId(itemid);
					vo.setItemKey(itemid);
					long longordercost = NumberUtils.getLongAmount(ordercost);
					vo.setTotalCost(longordercost);
					vo.setStoreDate(storedate);
					vo.setItemStatus(TbSlSupplyInventory.IN);
					list.add(vo);

				}
			}

		} catch (Exception e) {
			LogUtils.error(log, e);
		}
		return true;
	}

	public String getLastMonthMiddleDate(String maxdate) {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		try {
			Date dt = df.parse(maxdate);
			Date returndate = new Date(dt.getYear(), dt.getMonth() - 1, 15);
			return df.format(returndate);
		} catch (Exception e) {
			LogUtils.error(log, e);
		}
		return null;
	}

	@Override
	public boolean getOutstoreOrderData() throws BusinessException {
		// 送货记录
		// 对账单
		// TODO
		return true;
	}

	@Override
	public boolean getPayAccountData() throws BusinessException {
		// TODO Auto-generated method stub
		return true;
	}
	@Override
	public BankCardCheck isSupplyAccountCorrect() throws BusinessException {
		BankCardCheck bcc = new BankCardCheck();
		bcc.setCorrect(true);
		
		return bcc;
	}
}
